﻿using Help;
using Model;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace BLLA
{
    public partial class Order_Organization_T : BaseBLL<Model.Order_Organization_T>, IBLL.IOrder_Organization_TBLL
    {
        ObjectSerialize os = new ObjectSerialize();
        DataResult result = new DataResult();
        IBLL.IBLLSession bl = DI.SpringHelper.GetObject<IBLL.IBLLSession>("BLLSession");
        /// <summary>
        /// 企业帐号登录-获取企业账户信息
        /// </summary>
        /// <param name="OrgName">用户名</param>
        /// <param name="Pwd">密码</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string OrgLogin(string OrgName, string Pwd, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            //1.调用业务层方法 根据登陆名查询
            Model.Order_Organization_T usr = new Model.Order_Organization_T();
            try
            {
                usr = base.GetListBy("SELECT * FROM Order_Organization_T where OrgState=1 and  OrgName COLLATE Chinese_PRC_CS_AI  ='" + OrgName + "' and OrgPassword='" + Pwd + "'").First();
            }
            catch (Exception)
            {
                result.BS = "-1";
                result.Msg = "查询不到用户！";
                return os.StringOfObject(result, RETID);
            }
            //2.判断是否登陆成功
            if (usr != null && usr.OrgPassword == Pwd)
            {
                result.BS = "1";
                result.Msg = "登录成功！";
                result.rows = usr;
            }
            else
            {
                result.BS = "0";
                result.Msg = "帐号密码不匹配！";
            }
            return os.StringOfObject(result, RETID);
        }


        public string GetOrgListFromMer(int pageIndex, int pageSize, string MerID, Dictionary<string, string> Dic, string YZM, int RETID)
        {
            //string OrgName,string OrgPerson,string OrgPhone,
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 业务流程
            //int total = 0;
            List<Model.View_Order_Organization> OrgList = new List<Model.View_Order_Organization>();
            try
            {  
                StringBuilder SqlWhere = new StringBuilder();
                SqlWhere.Append("SELECT * FROM View_Order_Organization where OrgState=1 and OrgMers like '%" + MerID + "%'");
                foreach (var item in Dic)
                {
                    SqlWhere.Append(" and " + item.Key.ToString() + " like '%" + item.Value + "%'");
                }
                //OrgList = base.GetPagedList<int>(pageIndex,pageSize,ref total, u =>u.OrgState == 1,u=>u.OrgID);
                OrgList = base.DBSession.IView_Order_OrganizationDAL.GetListBy(SqlWhere.ToString());
                result.total = OrgList.Count;
            }
            catch (Exception)
            {
                result.BS = "-1";
                result.Msg = "查询不到用户！";
                return os.StringOfObject(result, RETID);
            }

            if (OrgList != null && OrgList.Count != 0)
            {
                result.BS = "1";
                result.Msg = "查询成功！";
                result.rows = OrgList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result.BS = "0";
                result.Msg = "查询不到数据！";
            }
            return os.StringOfObject(result, RETID);
            #endregion
        }
        /// <summary>
        /// 更新企业帐号信息
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="Data">json数据</param>
        /// <param name="tag">(1：增，2：改，3：删除)</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string SetOrganization(int OperID, string Data, int tag, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_Organization_T info = ParseClass<Model.Order_Organization_T>.StrDeserialize(Data, RETID);
                //string T = "";
                int ret = -1;
                // 根据操作标签Tag判断是什么操作
                switch (tag)
                {
                    case 1:
                        //T = "新增";
                        info.OrgID = int.Parse(GetSysKey.GetKey("OrgIDKey"));
                        info.OrgWaltBalance = info.OrgWaltLimit;
                        ret = base.Add(info);
                        break;
                    case 2:
                       // T = "修改";
                        Model.Order_Organization_T tmp = base.GetListBy(u => u.OrgID == info.OrgID).First();
                        info.OrgWaltBalance = tmp.OrgWaltBalance;
                        info.OrgWaltLimit = tmp.OrgWaltLimit; 
                        Help.FuZhi<Model.Order_Organization_T>.FZ(ref tmp, info);
                        ret = base.Modify(tmp);
                        break;
                    case 3:
                        //T = "删除";
                        List<Model.Order_Organization_T> list_tmp = base.GetListBy(u => u.OrgID == info.OrgID);
                        if (list_tmp != null && list_tmp.Count > 0)
                        {
                            tmp = list_tmp.First();
                            tmp.OrgState = 0;
                            ret = base.Modify(tmp);
                        }
                        break;
                }
                if (ret > 0)
                {

                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder errors = new StringBuilder();
                IEnumerable<DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                foreach (DbEntityValidationResult result in validationResult)
                {
                    ICollection<DbValidationError> validationError = result.ValidationErrors;
                    foreach (DbValidationError err in validationError)
                    {
                        errors.Append(err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                    }
                }
                //Console.WriteLine(errors.ToString());
                WriteLog.WriteW("SetOrganization异常：" + errors.ToString());
               
            }  
            catch (Exception ex)
            {
                result.BS = "-99";
                result.Msg = "更新失败" + ex.Message;
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }

        /// <summary>
        /// 查询接口-企业账户列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页码大小</param>
        /// <param name="Dic">查询的条件（Dic：list-Dic.Add("属性名", 需要查询的值)-没有查询时默认查询全部）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string GetOrgListForm(int pageIndex, int pageSize, Dictionary<string, string> Dic, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion 
            List<Model.View_Order_Organization> OrgList = new List<Model.View_Order_Organization>();
            try
            {
                StringBuilder SqlWhere = new StringBuilder();
                SqlWhere.Append("SELECT * FROM View_Order_Organization where OrgState=1");
                foreach (var item in Dic)
                {
                    SqlWhere.Append(" and " + item.Key.ToString() + " like '%" + item.Value + "%'");
                }
                //OrgList = base.GetPagedList<int>(pageIndex,pageSize,ref total, u =>u.OrgState == 1,u=>u.OrgID);
                OrgList = base.DBSession.IView_Order_OrganizationDAL.GetListBy(SqlWhere.ToString());

                result.total = OrgList.Count;
            }
            catch (Exception)
            {
                result.BS = "-1";
                result.Msg = "查询不到用户！";
                return os.StringOfObject(result, RETID);
            }
            if (OrgList != null && OrgList.Count != 0)
            {
                result.BS = "1";
                result.Msg = "查询成功！";
                result.rows = OrgList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                result.BS = "0";
                result.Msg = "查询不到数据！";
            }
            return os.StringOfObject(result, RETID);
        }

        /// <summary>
        /// 修改企业账户额度
        /// </summary>
        /// <param name="OperID">操作员ID</param>
        /// <param name="OrgID">企业账户ID</param>
        /// <param name="OrgWaltLimit">额度（单位：分）</param>
        /// <param name="YZM">验证码</param>
        /// <param name="RETID">数据格式(1:json;2:xml)</param>
        /// <returns></returns>
        public string SetOrganizationLimit(int OperID, int OrgID, int OrgWaltLimit, string YZM, int RETID)
        {
            #region 匹配验证码
            if (YZM != Help.ALL_DataV.YZM)
            {
                result.BS = "-88";
                result.Msg = "验证码错误！";
                return os.StringOfObject(result, RETID);
            }
            #endregion
            #region 执行操作
            try
            {
                Model.Order_Organization_T tmp = base.GetListBy(u => u.OrgID == OrgID).First();
                int i_增加的额度= OrgWaltLimit-tmp.OrgWaltLimit ;
                if (i_增加的额度<0)
                {
                    if (tmp.OrgWaltBalance < Math.Abs (i_增加的额度))
                    {
                        result.BS = "-1";
                        result.Msg = "余额不足，不允许再缩减额度";
                        return os.StringOfObject(result, RETID);
                    }
                }
                tmp.OrgWaltLastTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                tmp.OrgWaltBalance += i_增加的额度;
                tmp.OrgWaltLimit += i_增加的额度;
                int ret = base.Modify(tmp);

                if (ret > 0)
                {

                    result.BS = "1";
                    result.Msg = "更新成功";
                }
                else
                {
                    result.BS = "0";
                    result.Msg = "更新失败";
                }
            }
            catch (Exception ex)
            {
                result.BS = "-99";
                result.Msg = "更新失败" + ex.Message;
            }
            #endregion
            return os.StringOfObject(result, RETID);
        }
    }
}
